package com.example.config;

import com.example.pojo.user;
import com.example.service.userService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义的Realm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    userService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 设置用户权限
        // info.addStringPermission("user:add");
        info.addStringPermission("user:add");
        info.addStringPermission("user:update");

        //获取当前登录对象
        Subject subject = SecurityUtils.getSubject();
        // User currentUser = (User) subject.getPrincipal();

        //设置当前用户权限
        info.addStringPermission("user:add");
        info.addStringPermission("user:update");

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("认证");
        //String name = "root";
        //String password = "root";

        //读取封装的用户登录数据
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //连接数据库获取用户名、密码
        user user = userService.queryUserByName(userToken.getUsername());
        if (user == null) {
            //没有这个用户
            return null;
        }
        //密码认证
        return new SimpleAuthenticationInfo("", user.getPassword(), "");
    }
}
